package com.chezai.client.presenter;

import android.content.DialogInterface;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.SparseArray;

import com.chezai.client.R;
import com.chezai.client.bean.ImageInfo;
import com.chezai.client.bean.RandomPhoto;
import com.chezai.client.bean.ReadIdCardBean;
import com.chezai.client.bean.RetryUploadPhoto;
import com.chezai.client.bean.RetryUploadResult;
import com.chezai.client.bean.StudentSignInSucessEvent;
import com.chezai.client.bean.TakePhotoEntity;
import com.chezai.client.bean.TrainInfo;
import com.chezai.client.bean.UploadPhotoResult;
import com.chezai.client.bean.UserInfo;
import com.chezai.client.dao.manager.RandomPhotoDaoManager;
import com.chezai.client.dao.manager.TerminalBaseInfoDaoManager;
import com.chezai.client.dao.manager.UserInfoDaoManager;
import com.chezai.client.fragment.LearnCarFragment;
import com.chezai.client.fragment.StudentInfoFragment;
import com.chezai.client.global.Const;
import com.chezai.client.global.DeviceFactory;
import com.chezai.client.global.TerminalApplication;
import com.chezai.client.global.location.LocationMgr;
import com.chezai.client.inter.ITwoAndThreeView;
import com.chezai.client.server.TerminalSocketClientManager;
import com.chezai.client.server.TerminalSocketClientManager_8001;
import com.chezai.client.server.util.TransmissionMessageUtil;
import com.chezai.client.utils.BuildDataUtil;
import com.chezai.client.utils.DialogUtils;
import com.chezai.client.utils.LocationUtils;
import com.chezai.client.utils.TerminalUtils;
import com.chezai.client.utils.Util;
import com.jx.driving.request.Terminal0x0703Request;
import com.jx.driving.request.Terminal0x0900Request;
import com.jx.driving.response.AbstractResponse;
import com.jx.driving.response.Terminal0x8702Response;
import com.jx.driving.response.Terminal0x8703Response;
import com.jx.driving.transmission.Terminal0x0102Transmission;
import com.jx.driving.transmission.Terminal0x0305Transmission;
import com.jx.driving.transmission.Terminal0x0401Transmission;
import com.jx.driving.transmission.Terminal0x0402Transmission;
import com.jx.driving.transmission.Terminal0x8102Transmission;
import com.jx.driving.transmission.Terminal0x8401Transmission;
import com.jx.driving.transmission.Terminal0x8402Transmission;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 科二科三Presenter
 * Created by likunyang on 2017/9/15.
 */

public class TwoAndThreePresenter extends BasePresenter<ITwoAndThreeView> implements DialogInterface.OnDismissListener {
    private final TransmissionMessageUtil messageUtil;
    private String TAG = this.getClass().getSimpleName();
    private short loginType;
    private int mPhotoEventType;
    private int mSequence;
    private UserInfo mStudentInfo;
    private boolean isReadRFID;//刷卡登录
    private boolean isLoginFace;//人脸登录
    private String tempIdCard;
    private boolean isOnlyFaceLogin;//只用人脸登录
    private boolean isOnlyRFIDLogin = true;//只刷卡登录
    private boolean isReadingIdCard;
    private SparseArray<Long> randomPhotoSequenceCache = new SparseArray<>();
    private boolean isEndRetryUploadPhoto = false;//是否为结束教学重传照片
    private long mClassRecordId;
    private Disposable mRetryDisposable;

    public TwoAndThreePresenter() {
        messageUtil = new TransmissionMessageUtil();
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    /**
     * StudentInfoFragment
     * 学员登录拍照上传完成后
     *
     * @param trainInfo 训练信息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventTrainInfo(TrainInfo trainInfo) {
        if (isViewAttached())
            mvpView.switchFragment(Const.LEARN_CAR_FRAGMENT_TAG, trainInfo.classRecordId, trainInfo.trainPart, false);
    }

    private void showToast(String msg) {
        if (isViewAttached()) mvpView.showToast(msg);
    }

    /**
     * @return 可登录方式
     */
    public byte[] getLoginType() {
        int loginType = TerminalBaseInfoDaoManager.getInstance().getTerminalBaseInfo().getLoginType();
        return Util.intToByte7(loginType);
    }

    /**
     * 根据选择的登录方式，选择不同的请求
     *
     * @param loginType 登录类型
     */
    public void gotoLoginWithLoginType(short loginType) {
        this.loginType = loginType;
        switch (loginType) {
            case Const.LOGIN_TYPE_FACE:
                isOnlyFaceLogin = true;
                if (isViewAttached()) mvpView.takeStudentFaceLogin();
                break;
            case Const.LOGIN_TYPE_VERT:
            case Const.LOGIN_TYPE_WX:
                showToast("暂不支持");
                break;
            case Const.LOGIN_TYPE_IDCARD:
                isReadingIdCard = true;
                DialogUtils.showProgressBarDialog(mContext, "读卡中...", this);
                DeviceFactory.hardware.readIDCard(mContext);
                break;
            case Const.LOGIN_TYPE_APP:
                isOnlyFaceLogin = false;
                tell0x0401Tranmission(loginType, null);
                break;
            case Const.LOGIN_TYPE_RFID:
                isOnlyFaceLogin = false;
                isReadRFID = true;
                isLoginFace = false;
                String channelModel = TerminalApplication.channelModel;
                if (Const.QHYC_C103.equals(channelModel)) {
                    if (isViewAttached()) mvpView.showReadCardDialog();
                } else {
                    String cardNumber = DeviceFactory.hardware.readIcCard(mContext);
                    tell0x0401Tranmission(loginType, cardNumber);
                }
                break;
        }
    }


    private void tell0x0102Transmission(String coachUnifiedNum) {
        DialogUtils.showProgressBarDialog(mContext, R.string.coach_sign_out);
        Terminal0x0102Transmission ox0102 = new Terminal0x0102Transmission();
        ox0102.setCoachNo(coachUnifiedNum);
        ox0102.setGnss(LocationUtils.getGnssPackage(LocationMgr.getBestLocation()));
        //harisucici 上报监管
        TerminalSocketClientManager_8001.getInstance().tellWithNoAuth(messageUtil.buildTerminal0x0900Request(ox0102, false, true));
        TerminalSocketClientManager.getInstance().tellWithNeedAuth(messageUtil.buildTerminal0x0900Request(ox0102, false, true));
    }

    /**
     * 读取身份证
     *
     * @param cardEntry
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventReadIDCard(ReadIdCardBean cardEntry) {
        DialogUtils.dismissDialog();
        if (ReadIdCardBean.STATUS_NO_CONNECT == cardEntry.status) {
            showToast("请检查设备连接是否成功");
        } else if (ReadIdCardBean.STATUS_ERROR == cardEntry.status) {
            showToast("未检测到身份证");
        } else if (ReadIdCardBean.STATUS_SUCESS == cardEntry.status) {
            isReadingIdCard = false;
            tell0x0401Tranmission(Const.LOGIN_TYPE_IDCARD, cardEntry.uid);
        }
    }

    /**
     * @param ox8102 教练登出应答
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8102Transmission(Terminal0x8102Transmission ox8102) {
        DialogUtils.dismissDialog();
        short result = ox8102.getResult();
        switch (result) {
            case 1://登出成功
                BuildDataUtil.clearCoachClassId();
                if (isViewAttached()) mvpView.coachSignOutSucess();
                break;
            case 2://登出失败
                showToast("登出失败请重试");
                break;
            case 9://其他错误
                showToast("其他错误");
                break;
        }
    }

    /**
     * 根据用户身份 发送0x0401 身份认证透传消息
     *
     * @param type       登录方式
     * @param cardNumber IC卡号
     */
    public void tell0x0401Tranmission(short type, String cardNumber) {
        this.loginType = type;
        DialogUtils.showProgressBarDialog(mContext, R.string.get_user_identity);
        Terminal0x0401Transmission ox0401 = new Terminal0x0401Transmission();
        ox0401.setType(type);
        ox0401.setUserType(Const.LOGIN_ROLE_STUDENT);
        if (Const.LOGIN_TYPE_RFID == type || Const.LOGIN_TYPE_IDCARD == type) {
            ox0401.setCardCode(cardNumber);
        }
        TransmissionMessageUtil messageUtil = new TransmissionMessageUtil();
        TerminalSocketClientManager.getInstance().tellWithNeedAuth(messageUtil.buildTerminal0x0900Request(ox0401, false, true));
    }

    /**
     * @param ox8401 身份认证
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8401Transmission(Terminal0x8401Transmission ox8401) {
        DialogUtils.dismissDialog();
        //请求身份认证信息应答
        switch (ox8401.getResult()) {
            case 0:
                ox8401Sucess(ox8401);
                break;
            case 1:
                showToast("获取信息失败");
                break;
            case 9:
                showToast("其他错误");
                break;
        }
    }

    private void ox8401Sucess(Terminal0x8401Transmission ox8401) {
        switch (loginType) {
            case Const.LOGIN_TYPE_VERT:
            case Const.LOGIN_TYPE_WX:
                showToast("暂不支持");
                break;
            case Const.LOGIN_TYPE_APP:
                if (isViewAttached()) mvpView.showQRDialog(new String(ox8401.getContent()));
                break;
            case Const.LOGIN_TYPE_RFID:
            case Const.LOGIN_TYPE_FACE:
                String idCardNum = new String(ox8401.getContent());
                if (isOnlyRFIDLogin || isOnlyFaceLogin) {
                    tell0x0402Transmission(idCardNum);
                } else {
                    if (isReadRFID) {
                        isReadRFID = false;
                        tempIdCard = idCardNum;
                        if (isViewAttached()) mvpView.takeStudentFaceLogin();
                    }
                    if (isLoginFace) {
                        if (TextUtils.equals(tempIdCard, idCardNum)) {
                            tell0x0402Transmission(idCardNum);
                        } else {
                            showToast("身份认证不通过");
                        }
                        isLoginFace = false;
                    }
                }
                break;
            case Const.LOGIN_TYPE_IDCARD:
                String idCard = new String(ox8401.getContent());
                tell0x0402Transmission(idCard);
                break;
        }
    }

    /**
     * 扫码成功，APP端点开始教学 之后
     *
     * @param ox8702 服务下发教练，学员信息，并获取统一编号
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8702Response(Terminal0x8702Response ox8702) {
        if (isViewAttached()) mvpView.dissmissDialog();
        tell0x0402Transmission(ox8702.getCardCode());
    }

    /**
     * 根据用户身份 获取统一编号
     *
     * @param IDNumber 身份证号
     */
    private void tell0x0402Transmission(String IDNumber) {
        DialogUtils.showProgressBarDialog(mContext, R.string.get_user_info);
        mStudentInfo = UserInfoDaoManager.getInstance().insertUserInfoOrFind(IDNumber);
        Terminal0x0402Transmission ox0402 = new Terminal0x0402Transmission();
        ox0402.setType((short) 6);
        ox0402.setNo(IDNumber);
        TerminalSocketClientManager.getInstance().tellWithNeedAuth(messageUtil.buildTerminal0x0900Request(ox0402, false, true));
    }

    /**
     * 学员统一编号信息应答
     *
     * @param ox8402 返回统一编号 0x0402
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8402Transmission(Terminal0x8402Transmission ox8402) {
        short result = ox8402.getResult();
        //0：成功；1：失败（失败时无后续字段）；9：其他错误
        switch (result) {
            case 0:
                DialogUtils.showProgressBarDialog(mContext, R.string.get_user_info);
                String no = ox8402.getNo();//统一编号
                mStudentInfo.setUnifiedNum(no);
                mStudentInfo.setUserType(UserInfo.USER_STUDENT);
                UserInfoDaoManager.getInstance().update(mStudentInfo);
                Terminal0x0703Request ox0703 = new Terminal0x0703Request();
                ox0703.setUserType(Const.LOGIN_ROLE_STUDENT);
                ox0703.setUnifiedNum(no);
                TerminalSocketClientManager.getInstance().tellWithNeedAuth(ox0703);
                break;
            case 1:
                showToast("学员没有统一编号信息");
                DialogUtils.dismissDialog();
                break;
            case 9:
                showToast("其他错误");
                DialogUtils.dismissDialog();
                break;
        }
    }

    /**
     * 获取学员信息
     * 展示右侧项目内容
     *
     * @param ox8703 用户信息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8703Response(Terminal0x8703Response ox8703) {
        DialogUtils.dismissDialog();
        switch (ox8703.getResult()) {
            case 0:
                mStudentInfo.setName(TextUtils.isEmpty(ox8703.getName()) ? "" : ox8703.getName());
                mStudentInfo.setSex(ox8703.getSex());
                mStudentInfo.setPhone(ox8703.getPhone());
                mStudentInfo.setPhotoUrl(ox8703.getPhotoUrl());
                mStudentInfo.setDrivingType(ox8703.getDrivingType());
                UserInfoDaoManager.getInstance().update(mStudentInfo);
                if (isViewAttached()) {
                    mvpView.switchFragment(Const.STUDENT_INFO_FRAGMENT_TAG, mStudentInfo.get_ID(), "", true);
                }
                break;
            case 1:
                showToast("未找到学员信息");
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventTakePhoto(TakePhotoEntity takePhoto) {
        EventBus.getDefault().removeStickyEvent(takePhoto);
        mPhotoEventType = takePhoto.photoEventType;
        if (TakePhotoEntity.TAKE_PHOTO_SUCESS == takePhoto.status) {
            if (mPhotoEventType == Const.PhotoEventType.STUDENT_SIGN_IN) {
                if (mvpView.getCurrentFragment() instanceof StudentInfoFragment) {
                    ((StudentInfoFragment) mvpView.getCurrentFragment()).tell0x0201Transmission(takePhoto);
                }
            } else {
                takePhotoSucess(takePhoto);
            }
        } else {
            mvpView.showAlertDialog("拍照失败请重试！", mPhotoEventType);
        }
    }

    /**
     * 学员上报登录成功
     * StudentInfoFragment.onEvent0x8201Transmission
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventStudentSignInSucess(StudentSignInSucessEvent event) {
        mPhotoEventType = event.photo.photoEventType;
        takePhotoSucess(event.photo);
    }


    private void takePhotoSucess(final TakePhotoEntity takePhoto) {
        if (takePhoto.photoEventType != Const.PhotoEventType.STUDENT_LEARNING && takePhoto.photoEventType != Const.PhotoEventType.ZHUAPAI) {
            DialogUtils.showProgressBarDialog(mContext, R.string.upload_image);
        }
        if (TextUtils.isEmpty(takePhoto.photoPath)) return;
        Observable.create(new ObservableOnSubscribe<UploadPhotoResult>() {
            @Override
            public void subscribe(ObservableEmitter<UploadPhotoResult> emitter) throws Exception {
                ImageInfo imageInfo = TerminalUtils.getImageInfo(takePhoto.photoPath);
                long randomPhotoId = -1;
                Terminal0x0305Transmission transmission;
                if (takePhoto.photoEventType == Const.PhotoEventType.STUDENT_LEARNING) {
                    Logger.t(TAG).d("抓拍照片上传");
                    randomPhotoId = takePhoto.randomPhotoId;
                    RandomPhoto randomPhoto = RandomPhotoDaoManager.getInstance().findPeriodRecordPhoto(randomPhotoId);
                    transmission = Util.parseGsonJsonToObject(randomPhoto.get_0305());
                    int mPackageCount = TerminalUtils.getImagePackageCount(imageInfo.imageBuffer);
                    transmission.setPackageCount(mPackageCount);
                    transmission.setDataLength(imageInfo.imageBuffer.length);
                    Logger.t(TAG).d(transmission.toString());
                    String trans = Util.parseObjectToGsonJson(transmission);
                    randomPhoto.set_0305(trans);
                    randomPhoto.setUploadStatus(Const.UPLOAD_FAILED);
                    randomPhoto.setPhotoPath(takePhoto.photoPath);
                    RandomPhotoDaoManager.getInstance().update(randomPhoto);
                }else{
                    transmission = getTerminal0x0305Transmission(takePhoto.photoEventType, imageInfo.imageNo, imageInfo.imageBuffer);
                }
                Terminal0x0900Request req = new TransmissionMessageUtil().buildTerminal0x0900Request(transmission, false, false);
                TerminalSocketClientManager.getInstance().tellWithNeedAuth(req);
                Integer sequence = TerminalUtils.sendToServer(imageInfo.imageBuffer, imageInfo.imageNo);
                if (sequence != null) {
                    mSequence = sequence;
                    emitter.onNext(new UploadPhotoResult(sequence, takePhoto.photoEventType, randomPhotoId));
                }
            }
        }).observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<UploadPhotoResult>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(UploadPhotoResult result) {
                        Logger.t(TAG).d("照片上传完毕: sequence:" + result.sequence);
                        if (result.photoEventType == Const.PhotoEventType.STUDENT_LEARNING) {
                            randomPhotoSequenceCache.put(result.sequence, result.periodRecordId);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 重传失败照片
     *
     * @param photo 照片信息
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventRetryUploadPhoto(RetryUploadPhoto photo) {
        EventBus.getDefault().removeStickyEvent(photo);
        isEndRetryUploadPhoto = photo.isEnd;
        if (isEndRetryUploadPhoto) {
            mClassRecordId = photo.classRecordId;
            randomPhotoSequenceCache.clear();
            endRetryUploadImage(photo.classRecordId);
        } else {
            retryUploadImage(photo);
        }
    }

    //結束教學补传照片
    private void endRetryUploadImage(final long classRecordId) {
        RandomPhoto randomPhoto = RandomPhotoDaoManager.getInstance().findOneUploadFailedRecord(classRecordId);
        DialogUtils.showProgressBarDialog(mContext, R.string.try_upload_photo);
        if (randomPhoto != null) {
            Observable.just(randomPhoto)
                    .map(new Function<RandomPhoto, Integer>() {
                        @Override
                        public Integer apply(RandomPhoto randomPhoto) throws Exception {
                            if (TerminalSocketClientManager.getInstance().isAuthenticated()) {
                                ImageInfo imageInfo = TerminalUtils.getImageInfo(randomPhoto.getPhotoPath());
                                Terminal0x0305Transmission _0x0305Trans = Util.parseGsonJsonToObject(randomPhoto.get_0305());
                                Terminal0x0900Request req = new TransmissionMessageUtil().buildTerminal0x0900Request(_0x0305Trans, false, false);
                                TerminalSocketClientManager.getInstance().tellWithNeedAuth(req);
                                Integer sequence = TerminalUtils.sendToServer(imageInfo.imageBuffer, imageInfo.imageNo);
                                if (sequence != null) {
                                    Logger.t("TryUpload").d("结束教学补传传照片 sequence: " + sequence);
                                    randomPhotoSequenceCache.put(sequence, randomPhoto.get_ID());
                                }
                            } else {
                                return -1;
                            }
                            return 1;
                        }
                    }).observeOn(Schedulers.io())
                    .subscribeOn(Schedulers.io())
                    .subscribe(new Observer<Integer>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                        }

                        @Override
                        public void onNext(Integer integer) {
                            if (integer == -1) {
                                endRetryUploadImage(mClassRecordId);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onComplete() {
                        }
                    });
        } else {
            EventBus.getDefault().post(new RetryUploadResult(true, RetryUploadResult.UPLOAD_PHOTO_OVER));
        }
    }

    /**
     * 练车中重传照片
     *
     * @param photo
     */
    private void retryUploadImage(final RetryUploadPhoto photo) {
        if (mRetryDisposable != null) {
            mRetryDisposable.dispose();
        }
        Observable.create(new ObservableOnSubscribe<List<RandomPhoto>>() {
            @Override
            public void subscribe(ObservableEmitter<List<RandomPhoto>> emitter) throws Exception {
                List<RandomPhoto> uploadFailedRecord = RandomPhotoDaoManager.getInstance().findUploadFailedRecord(photo.classRecordId);
                Logger.t("TryUpload").d("练车中需补传：" + uploadFailedRecord.size() + "张照片");
                emitter.onNext(uploadFailedRecord);
            }
        }).map(new Function<List<RandomPhoto>, Integer>() {
            @Override
            public Integer apply(List<RandomPhoto> randomPhotos) throws Exception {
                for (int i = 0; i < randomPhotos.size(); i++) {
                    RandomPhoto randomPhoto = randomPhotos.get(i);
                    randomPhoto.setTryCount(randomPhoto.getTryCount() + 1);
                    RandomPhotoDaoManager.getInstance().update(randomPhoto);
                    removeRandomPhotoId(randomPhoto.get_ID());
                    if (randomPhoto.getTryCount() >= Const.TRY_COUNT) {
                        continue;
                    }
                    Logger.t("TryUpload").d("正在重传第 " + i + " 张照片：" + randomPhoto.getPhotoPath());
                    if (TerminalSocketClientManager.getInstance().isAuthenticated()) {
                        ImageInfo imageInfo = TerminalUtils.getImageInfo(randomPhoto.getPhotoPath());
                        Terminal0x0305Transmission _0x0305Trans = Util.parseGsonJsonToObject(randomPhoto.get_0305());
                        Terminal0x0900Request req = new TransmissionMessageUtil().buildTerminal0x0900Request(_0x0305Trans, false, false);
                        TerminalSocketClientManager.getInstance().tellWithNeedAuth(req);
                        Integer sequence = TerminalUtils.sendToServer(imageInfo.imageBuffer, imageInfo.imageNo);
                        if (sequence != null) {
                            Logger.t("TryUpload").d("正在重传第 " + i + " 张照片 sequence: " + sequence);
                            randomPhotoSequenceCache.put(sequence, randomPhoto.get_ID());
                        }
                    }
                }
                return 1;
            }
        }).observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mRetryDisposable = d;
                    }

                    @Override
                    public void onNext(Integer o) {
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.t("TryUpload").d("----------重传照片错误---------" + e.getMessage());
//                        EventBus.getDefault().postSticky(new RetryUploadResult(photo.isEnd, RetryUploadResult.UPLOAD_PHOTO_OVER));
                    }

                    @Override
                    public void onComplete() {
                        Logger.t("TryUpload").d("----------重传照片任务 OnComplete---------");
                    }
                });
    }

    private void removeRandomPhotoId(Long randomPhotoId) {
        int key = randomPhotoSequenceCache.indexOfValue(randomPhotoId);
        if (key >= 0) {
            randomPhotoSequenceCache.remove(key);
        }
    }

    /**
     * 初始化照片信息
     *
     * @param imageNo 照片编号
     * @param buffer  照片二进制
     * @return 照片初始化协议
     */
    private Terminal0x0305Transmission getTerminal0x0305Transmission(int photoEventType, String imageNo, byte[] buffer) {
        Terminal0x0305Transmission transmission = new Terminal0x0305Transmission();
        transmission.setImageNo(imageNo);
        //1：平台拍照指令后上传自动请求上传；2：平台查询后要求上传；129：终端主动拍照上传；255：停止拍摄并上传图片
        transmission.setUploadType(Const.UploadPhotoType.TERMINAL_UPLOAD);
        if (photoEventType == Const.PhotoEventType.STUDENT_SIGN_IN
                || photoEventType == Const.PhotoEventType.STUDENT_SIGN_OUT
                || photoEventType == Const.PhotoEventType.STUDENT_LEARNING
                || photoEventType == Const.PhotoEventType.ZHUAPAI) {
            transmission.setUserNo(mvpView.getStudentInfo() == null ? mStudentInfo.getUnifiedNum() : mvpView.getStudentInfo().getUnifiedNum());
            transmission.setClassId(BuildDataUtil.getStudentClassId());
            if (photoEventType == Const.PhotoEventType.ZHUAPAI) {
                transmission.setUploadType(Const.UploadPhotoType.AUTO_UPLOAD);
            }
        } else if (photoEventType == Const.PhotoEventType.TEACHE_SIGN_OUT) {
            transmission.setUserNo(mvpView.getCoachInfo().getUnifiedNum());
            transmission.setClassId(BuildDataUtil.getCoachClassId());
        }
        transmission.setCameraChannel((short) 0);
        transmission.setSize((short) 2);
        transmission.setEventType((short) photoEventType);
        transmission.setDataLength(buffer.length);
        transmission.setGnss(LocationUtils.getGnssPackage(LocationMgr.getBestLocation()));
        transmission.setTrustable((short) 100);
        int mPackageCount = TerminalUtils.getImagePackageCount(buffer);
        transmission.setPackageCount(mPackageCount);
        transmission.setAttachementList(TerminalApplication.getTerminalContext().getLocationAttachement());
        return transmission;
    }

    /**
     * 上传照片
     * 照片上传成功，进入相关界面
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventUploadImage(AbstractResponse response) {
        int msgId = response.getId();
        if (msgId == 0x900) {
            int sequence = response.getSequence();
            Logger.t(TAG).d("sequence :" + response.getSequence() + "__result:" + response.getResult());
            if (response.getResult() == 0) {
                uploadRandomPhoto(sequence);
                if (sequence == mSequence) {
                    Fragment fragment = mvpView.getCurrentFragment();
                    DialogUtils.dismissDialog();
                    switch (mPhotoEventType) {
                        case Const.PhotoEventType.STUDENT_FACE_LOGIN://人脸登录
                            isLoginFace = true;
                            tell0x0401Tranmission(Const.LOGIN_TYPE_FACE, null);
                            break;
                        case Const.PhotoEventType.TEACHE_SIGN_OUT://教练登出
                            tell0x0102Transmission(mvpView.getCoachInfo().getUnifiedNum());
                            break;
                        case Const.PhotoEventType.STUDENT_SIGN_IN://学员登录
                            if (fragment instanceof StudentInfoFragment) {
                                ((StudentInfoFragment) fragment).saveData();
                            }
                            break;
                        case Const.PhotoEventType.STUDENT_SIGN_OUT://学员登出
                            if (fragment instanceof LearnCarFragment) {
                                ((LearnCarFragment) fragment).tell0x0202Transmission();
                            }
                            break;
                    }
                }
            }
        }
    }

    private void uploadRandomPhoto(int sequence) {
        Long randomPhotoId = randomPhotoSequenceCache.get(sequence);
        if (randomPhotoId != null) {
            Logger.t("TryUpload").d("----------照片上传完成----- sequence: " + sequence + "---- photoId: " + randomPhotoId);
            RandomPhoto record = RandomPhotoDaoManager.getInstance().findPeriodRecordPhoto(randomPhotoId);
            record.setUploadStatus(Const.UPLOAD_SUCESS);
            RandomPhotoDaoManager.getInstance().update(record);
            randomPhotoSequenceCache.remove(sequence);
            if (isEndRetryUploadPhoto) {
                endRetryUploadImage(mClassRecordId);
            }
        }
    }


    @Override
    public void onDismiss(DialogInterface dialog) {
        if (isReadingIdCard) {
            DeviceFactory.hardware.closeSerialPort();
        }
    }
}
